package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author LiangTianQi
 * @describe
 * @date 2020/11/9 9:55
 */
@Service(interfaceClass = CheckGroupSevice.class)
public class CheckGroupServiceImpl implements CheckGroupSevice {

    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    @Transactional
    public void add(CheckGroup checkGroup,Integer[] checkitemIds) {
        //向检查组中添加数据
        checkGroupDao.add(checkGroup);
        Integer id = checkGroup.getId();
        //向中间表中添加数据
        for (Integer checkitemId : checkitemIds) {
            checkGroupDao.addByCGIDandCTID(id,checkitemId);
        }
    }

    @Override
    @Transactional
    public boolean delete(Integer id) {
        //先通过id查询套餐与检查组中是否有关系，如果有则直接返回false，如果没有则进行删除
        List<Integer> list = checkGroupDao.getSetmealIdByCheckGroupId(id);
        if (list.size()==0){
            //先删除中间表中的数据再删除自己，表中有外键约束
            checkGroupDao.deleteById(id);
            checkGroupDao.delete(id);
            return true;
        }else{
            return false;
        }

    }

    @Override
    @Transactional
    public void update(CheckGroup checkGroup,Integer[] checkitemIds) {
        //更新checkgroup的基本数据
        checkGroupDao.update(checkGroup);
        //根据id删除全部的中间表的信息
        checkGroupDao.deleteById(checkGroup.getId());
        //向中间表中添加关系
        for (Integer checkitemId : checkitemIds) {
            checkGroupDao.addByCGIDandCTID(checkGroup.getId(),checkitemId);
        }
    }

    @Override
    public CheckGroup get(Integer id) {
        return checkGroupDao.get(id);
    }


    @Override
    public PageResult getByConditions(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<CheckGroup> checkGroups = checkGroupDao.getByConditions(queryPageBean.getQueryString());
        PageInfo info = new PageInfo(checkGroups);
        PageResult pageResult = new PageResult(info.getTotal(),info.getList());
        return pageResult;
    }

    @Override
    public List<Integer> getCheckItemIdsById(Integer id) {
        return checkGroupDao.getCheckItemIdsById(id);
    }

    @Override
    public List<CheckGroup> getAll() {
        return checkGroupDao.getAll();
    }
}
